package com.example.mc_java;

import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;


public class MainActivity extends FlutterActivity {

    String TAG = "Flutter";
	//基本消息通道
	private BasicMessageChannel<Object> mObjectBasicMessageChannel;
	private MediaPlayer mediaPlayer;
	private Timer mTimer;
	private TimerTask mTimerTask;
	private int index = 0;
	private ArrayList<Bean> musics;
	private ArrayList<HashMap<String, Object>> musicList;
	private Bean bean;

    //isOpen 是否暂停
	private boolean isOpen =false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Cursor cursor0 = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        Cursor cursor1 = getContentResolver().query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        ArrayList<HashMap<String, Object>> list0 = scanAllAudioFiles(cursor0);
        ArrayList<HashMap<String, Object>> list1 = scanAllAudioFiles(cursor1);
        musicList = list1;
//        musicList.addAll(list1);
//        musicList.addAll(list0);
        Log.d("flutter","musics----------------"+musicList.size());

        musics = new ArrayList<Bean>();
        for(int i=0;i<musicList.size();i++){
            String musicFileUrl = musicList.get(i).get("musicFileUrl").toString();
            String musicTitle  = musicList.get(i).get("musicTitle").toString();
            String musicUrl = musicList.get(i).get("music_url").toString();
            String musicId = musicList.get(i).get("musicId").toString();
            String musicDuration = musicList.get(i).get("music_duration").toString();
            String musicFileName = musicList.get(i).get("music_file_name").toString();
            String musicAuthor = musicList.get(i).get("music_author").toString();
            Bean _bean = new Bean(musicFileUrl,musicTitle,musicUrl,musicId,musicDuration,musicFileName,musicAuthor);
            musics.add(_bean);
        }

        Log.d("flutter","musics"+musics.size()+musics);
        android.util.Log.d(TAG,"musics"+musics.size());
        if(musics.size()>0) {
            bean = musics.get(0);
//            sendDate(musics);
        };

        // android.util.Log.d(TAG,"bean.musicTitle"+bean.musicTitle!=null?bean.musicTitle:"空");
        mediaPlayer = new MediaPlayer();
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
//                android.util.Log.e(TAG, " isOpen: "+isOpen+" 音乐运行的时间: "+timeParse(mediaPlayer.getCurrentPosition()));
            }
        };
        mTimer.schedule(mTimerTask, 0, 100);

    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        MethodChannel channel3 = new MethodChannel(
                flutterEngine.getDartExecutor().getBinaryMessenger(),
                "methodChannel"
        );

        channel3.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall methodCall, @NonNull MethodChannel.Result result) {
                switch(methodCall.method){
                    case "initMusics" :
                        Log.d("FLUTTER","初始化音乐");
                        initMusics(result);
                        break;
                    case "playMusic" :
                        index = (Integer) methodCall.argument("index");
                        playMusic(musics.get(index).musicFileUrl);
                        Log.d("FLUTTER","开始音乐");
                        result.success("startMusic方法通道: 开始音乐");
                        break;
                    case "startMusic" :
                        startMusic();
                        Log.d("FLUTTER","开始音乐");
                        result.success("startMusic方法通道: 开始音乐");
                        break;
                    case "stopMusic" :
                        stopMusic();
                        Log.d("FLUTTER","暂停音乐");
                        result.success("stopMusic方法通道: 暂停音乐");
                        break;
                    case "lastClick" :
                        lastClick();
                        Log.d("FLUTTER","上一首音乐");
                        result.success("lastClick方法通道: 上一首音乐");
                        break;
                    case "nextClick" :
                        nextClick();
                        Log.d("FLUTTER","下一首音乐");
                        result.success("nextClick方法通道: 下一首音乐");
                        break;
                    default :
                        Log.d("FLUTTER","无该方法");
                        result.success("default方法通道: 无该方法");
                }
            }
        });
    }


    ///获取手机中的音乐列表信息
    public ArrayList<HashMap<String, Object>> scanAllAudioFiles(Cursor cursor){
        Log.d("flutter","musics----------------0");
        //生成动态集合，用于存储数据
        ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
        Log.d("flutter","musics----------------1" + mylist.size());
        //查询媒体数据库
//        Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        Log.d("flutter","musics----------------2");
        //遍历媒体数据库
        if(cursor.moveToFirst()){
            Log.d("flutter","musics----------------3");
            while (!cursor.isAfterLast()) {
                Log.d("flutter","musics----------------4");
                //歌曲编号
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                //歌曲名
                String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                //歌曲的专辑名：MediaStore.Audio.Media.ALBUM
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                //歌曲的歌手名： MediaStore.Audio.Media.ARTIST
                String author = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                //歌曲文件的路径 ：MediaStore.Audio.Media.DATA
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                //歌曲的总播放时长 ：MediaStore.Audio.Media.DURATION
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                //歌曲文件的大小 ：MediaStore.Audio.Media.SIZE
                Long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

                if(size>1024*800){//如果文件大小大于800K，将该文件信息存入到map集合中
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("musicId", id);
                    map.put("musicTitle", tilte);
                    map.put("musicFileUrl", url);
                    map.put("music_file_name", tilte);
                    map.put("music_author",author);
                    map.put("music_url",url);
                    map.put("music_duration",duration);
                    mylist.add(map);
                }
                cursor.moveToNext();
            }
            Log.d("flutter","musics----------------5");
        }
        Log.d("flutter","musics----------------6");
        android.util.Log.e("TAG", "musicList: ---------------" + mylist.size() );

        Log.d("flutter","musics----------------7" + mylist.size());
        //返回存储数据的集合
        return mylist;
    }

    //时间转换
    public static String timeParse(long duration) {
        String time = "" ;
        long minute = duration / 60000 ;
        long seconds = duration % 60000 ;
        long second = Math.round((float)seconds/1000) ;
        if( minute < 10 ){
            time += "0" ;
        }
        time += minute+":" ;
        if( second < 10 ){
            time += "0" ;
        }
        time += second ;
        return time ;
    }

    @Override
    //请求权限的结果
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    void initMusics(@NonNull MethodChannel.Result result){
        ArrayList<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        int i=0;
        for (Bean music : musics) {
            Map<String, Object> map = new HashMap<>();
            map.put("musicFileUrl",music.musicFileUrl);
            map.put("musicTitle",music.musicTitle);
            map.put("musicUrl",music.musicUrl);
            map.put("musicId",music.musicId);
            map.put("musicDuration",music.musicDuration);
            map.put("musicFileName",music.musicFileName);
            map.put("musicAuthor",music.musicAuthor);
            mapList.add(map);
            i++;
        }
        result.success(mapList);
    };

    //播放音乐
    public void playMusic(String path) {
        if(isOpen==false){
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                mediaPlayer.start();
                isOpen = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            if(mediaPlayer.isPlaying()){
                mediaPlayer.pause();
            }else{
                mediaPlayer.start();
            }
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                mediaPlayer.start();
                isOpen = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //开始或继续
    //暂停
    public void startMusic() {
        android.util.Log.e(TAG, "a isOpen: "+isOpen+" 是否正在播放: "+mediaPlayer.isPlaying());

        if(isOpen){
            android.util.Log.e(TAG, "0 isOpen: "+isOpen+" 是否正在播放start: "+mediaPlayer.isPlaying());
//			if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            android.util.Log.e(TAG, "0 isOpen: "+isOpen+" 是否正在播放end: "+mediaPlayer.isPlaying());

//			}
            isOpen = false;
        }else{
            android.util.Log.e(TAG, "1 isOpen: "+isOpen+" 是否正在播放start: "+mediaPlayer.isPlaying());
//			if(mediaPlayer.isPlaying()){
//				playMusic(bean.musicFileUrl);
//			}else{
            mediaPlayer.start();
            android.util.Log.e(TAG, "1 isOpen: "+isOpen+" 是否正在播放end: "+mediaPlayer.isPlaying());

//			}
            isOpen = true;
        }
    }

    //停止(结束)
    public void stopMusic() {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
        }
    }

    //上一首
    public void lastClick() {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
        int i = index;
        if(i==0){
            i = musicList.size()-1;
        }else{
            i = i-1;
        }
        bean = musics.get(i);
        index = i;
        playMusic(bean.musicFileUrl);
    }

    //下一首
    public void nextClick() {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
        int i = index;
        if(i==musicList.size()-1){
            i = 0;
        }else{
            i = i+1;
        }
        bean = musics.get(i);
        index = i;
        playMusic(bean.musicFileUrl);
    }
}
